package com.huwei.boxuegu.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.huwei.boxuegu.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

public class LoginActivity extends AppCompatActivity {

    EditText mUsername,mPassword;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mUsername = (EditText) findViewById(R.id.usernameedt);
        mPassword = (EditText) findViewById(R.id.passwordedt);
    }

    public void jumptoregister(View view){
        Intent intent = new Intent(this,RegisterActivity.class);
        startActivity(intent);
    }
    public void back(View view){
        finish();
    }

    public void login(View view){
        RequestParams params = new RequestParams("http://1633.applinzi.com/public/?s=App.User.Login");//请求的域名
        params.addQueryStringParameter("username", mUsername.getText().toString());
        params.addQueryStringParameter("password", mPassword.getText().toString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson  =new Gson();
                LoginModel loginModel = gson.fromJson(result,LoginModel.class);
                if (loginModel.code==200){
                    //保存登陆状态 1.文件保存 xml，2.数据库保存 shareperfence
                    //name 保存的文件的名称
                    SharedPreferences sp = getSharedPreferences("login", Context.MODE_PRIVATE); //别的进程读不到
                    SharedPreferences.Editor editor =sp.edit();
                    editor.putBoolean("islogin",true);
                    editor.putString("usrname",loginModel.data.username);
                    editor.commit();
                    finish();

                }else {
                    Toast.makeText(LoginActivity.this,"登陆失败" ,Toast.LENGTH_SHORT).show();
                }
                Log.i("LoginActivity","onSuccess loginModel coce:" +loginModel.code);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i("LoginActivity","onError result:" +ex.getMessage());
                Toast.makeText(LoginActivity.this,"登陆失败" ,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

}
